package com.chaosj.webmagic.convert;

import com.chaosj.webmagic.IConvertPage;
import com.chaosj.webmagic.dto.SearchEnums;
import us.codecraft.webmagic.Page;

import java.lang.reflect.ParameterizedType;

/**
 * @className: AbstractConvertPage
 * @description:
 * @author: caoyangjie
 * @date: 2021/8/11
 **/
public abstract class AbstractConvertPage<T> implements IConvertPage<SearchEnums> {

    /**
     * 创建对象
     * @return
     */
    public T createOrGet(Page page) {
        T instance = (T) page.getResultItems().getAll().getOrDefault("data", createInstance());
        page.putField("data", instance);
        return instance;
    }

    public String holdTarget(String target) {
        return SearchEnums.HOME.getTarget().replace("www","so")+target.substring(1);
    }

    private T createInstance(){
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        T instance = null;
        try {
            instance = (T) Class.forName(type.getActualTypeArguments()[0].getTypeName()).newInstance();
        } catch (InstantiationException e) {
        } catch (IllegalAccessException e) {
        } catch (ClassNotFoundException e) {
        }
        return instance;
    }
}
